<template>
  <div class="content">
    <!-- 顶部搜索栏 -->
    <div class="top">
      <a-card :bordered="false" style="margin-bottom: 10px">
        <a-button type="primary" @click="showModal" ghost
          ><PlusCircleOutlined />添加</a-button
        >
      </a-card>
    </div>

    <div>
      <a-spin tip="加载中..." :spinning="spinning">
        <a-card :bordered="false" style="height: 100vh">
          <a-list
            class="demo-loadmore-list"
            item-layout="horizontal"
            :data-source="data"
          >
            <template #renderItem="{ item }">
              <a-list-item>
                <template #actions>
                  <a-button @click="edit(item.id)" type="primary" ghost
                    ><FormOutlined
                  /></a-button>
                  <a-popconfirm
                    title="确认删除？"
                    ok-text="确认"
                    cancel-text="取消"
                    @confirm="removeById(item.id)"
                    @cancel="cancel"
                  >
                    <a-button type="primary" ghost danger>
                      <DeleteOutlined href="#" />
                    </a-button>
                  </a-popconfirm>
                </template>
                <a-list-item-meta :description="item.regionDetails">
                  <template #title>
                    <span style="font-weight: bold; font-size: 18px">
                      {{ item.receiver }}
                    </span>
                    <span
                      style="
                        font-size: 14px;
                        padding-left: 10px;
                        margin-right: 10px;
                      "
                    >
                      {{ item.phone }}
                    </span>
                    <a-tag v-if="item.status === 0 ? false : true" color="red"
                      ><span style="font-size: 12px">默认</span></a-tag
                    >
                  </template>
                  <template #avatar>
                    <a-avatar :src="item.avatar" />
                  </template>
                </a-list-item-meta>
              </a-list-item>
            </template>
          </a-list>
        </a-card>
      </a-spin>
    </div>
  </div>

  <!-- 新增弹出框 -->
  <div>
    <a-modal
      v-model:open="open"
      @cancel="handleCancel"
      title="添加收获地址"
      :footer="null"
    >
      <div style="padding: 30px 0 20px 50px">
        <a-form
          ref="formRef"
          :model="address"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-item ref="receiver" label="收货人" name="receiver">
            <a-input
              size="large"
              v-model:value="address.receiver"
            /> </a-form-item
          ><a-form-item ref="phone" label="手机号" name="phone">
            <a-input size="large" v-model:value="address.phone" />
          </a-form-item>
          <a-form-item label="验证码" ref="code" name="code">
            <a-input-search
              v-model:value="address.code"
              placeholder="请输入验证码"
              @search="onSearch"
              style="width: 100%"
              maxlength="6"
              minlength="6"
              size="large"
            >
              <template #enterButton>
                <a-button
                  @click="getCode"
                  :disabled="disabled"
                  style="
                    background-color: #409eff;
                    color: #fff;
                    font-size: 10px;
                  "
                  >{{ content }}</a-button
                >
              </template>
            </a-input-search>
          </a-form-item>
          <a-form-item ref="regions" label="所在地区" name="regions">
            <a-cascader
              size="large"
              v-model:value="address.regions"
              :options="options"
              placeholder="请选择地区"
              expand-trigger="hover"
            />
          </a-form-item>
          <a-form-item ref="detail" label="详细地址" name="detail">
            <a-textarea
              placeholder="请勿重复输入地区信息"
              size="large"
              v-model:value="address.detail"
            />
          </a-form-item>
          <a-form-item ref="status" label="默认地址" name="status">
            <a-switch v-model:checked="address.checked" />
          </a-form-item>
          <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button type="primary" @click="saveAddress">保存</a-button>
            <a-button style="margin-left: 10px" @click="handleCancel"
              >取消</a-button
            >
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
  </div>
</template>
<script setup>
import {
  PlusCircleOutlined,
  FormOutlined,
  DeleteOutlined,
} from "@ant-design/icons-vue";
import { ref, onMounted } from "vue";
import { save, list, remove, echo, update, getAreaData } from "@/api/address";
import { message } from "ant-design-vue";
import { useUserStore } from "@/stores/user";
import { useAuthorizationStore } from "@/stores/authorization";
import { sendMs } from "@/api/sendMs";

const spinning = ref(true);
onMounted(() => {
  getAddressList();
  getAllAreaData();
  spinning.value = false;
});

const data = ref([]);
//获取当前用户的收货地址
function getAddressList() {
  list(userStore.user.key).then((res) => {
    if (res.code === 200 && res.data != null) {
      data.value = res.data;
    }
  });
}

const options = ref([]);
//获取省市区数据
function getAllAreaData() {
  getAreaData().then((res) => {
    if (res.code === 200) {
      options.value = res.data;
    }
  });
}

const address = ref({
  id: null,
  userId: null,
  receiver: "",
  phone: "",
  detail: "",
  regions: [],
  region: "",
  checked: false,
  status: 0,
  code: "",
});
const authorizationStore = useAuthorizationStore();
const open = ref(false);
const showModal = () => {
  if (!authorizationStore.authorization) {
    message.error("需要先登录哦！");
  } else {
    open.value = true;
  }
};

//新增地址方法
const userStore = useUserStore();
function saveAddress() {
  formRef.value
    .validate()
    .then(() => {
      for (var i = 0; i < address.value.regions.length; i++) {
        address.value.region += address.value.regions[i];
      }
      if (address.value.id === null) {
        if (address.value.checked) {
          address.value.status = 1;
        } else {
          address.value.status = 0;
        }
        address.value.userId = userStore.user.key;
        save(address.value).then((res) => {
          if (res.code == 200) {
            message.success("收获地址添加成功啦！");
            getAddressList();
            open.value = false;
            address.value = {
              id: null,
              userId: null,
              receiver: "",
              phone: "",
              detail: "",
              region: "",
              checked: false,
              status: 0,
            };
          }
        });
      } else {
        if (address.value.checked) {
          address.value.status = 1;
        } else {
          address.value.status = 0;
        }
        update(address.value).then((res) => {
          if (res.code == 200) {
            message.success("收获地址修改成功啦！");
            getAddressList();
            open.value = false;
            address.value = {
              id: null,
              userId: null,
              receiver: "",
              phone: "",
              detail: "",
              region: "",
              checked: false,
              status: 0,
            };
          }
        });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消新增方法
function handleCancel() {
  address.value = {
    id: null,
    userId: null,
    receiver: "",
    phone: "",
    detail: "",
    region: "",
    checked: false,
    status: 0,
  };
  open.value = false;
}

//修改地址方法(数据回显)
function edit(id) {
  echo(id).then((res) => {
    if (res.code === 200) {
      address.value = res.data;
      open.value = true;
      address.value.region = "";
    }
  });
}

//删除地址方法
function removeById(id) {
  remove(id).then((res) => {
    if (res.code === 200) {
      message.success("删除成功!");
      getAddressList();
    }
  });
}

const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const formRef = ref();
const rules = {
  regions: [
    {
      required: true,
      message: "请输入所在地区",
      trigger: "change",
    },
  ],
  code: [
    {
      required: true,
      message: "请输入手机验证码",
      trigger: "change",
    },
  ],
  receiver: [
    {
      required: true,
      message: "请设置收获人",
      trigger: "change",
    },
  ],
  detail: [
    {
      required: true,
      message: "请输入详细地址",
      trigger: "change",
    },
  ],
  phone: [
    {
      required: true,
      message: "请输入手机号",
      trigger: "change",
    },
    {
      min: 11,
      max: 11,
      message: "长度为11个字符",
      trigger: "blur",
    },
  ],
};

//获取验证码前确认是否是真实手机号
const disabled = ref(false);
const content = ref("获取验证码");
function getCode() {
  //请求发送短信
  if (address.value.phone !== "") {
    sendMs(address.value.phone).then((res) => {
      if (res.code === 200) {
        message.success("发送成功!");
      }
    });
    var time = 180;
    //禁用获取验证码按钮
    disabled.value = true;
    // 开启定时器
    var timer = setInterval(function () {
      // 判断剩余秒数
      if (time == 0) {
        // 清除定时器和复原按钮
        clearInterval(timer);
        disabled.value = false;
        content.value = "获取验证码";
      } else {
        content.value = `${time}秒后重新获取`;
        time--;
      }
    }, 1000);
  } else {
    message.error("请输入手机号");
  }
}
</script>
<style scoped>
.demo-loadmore-list {
  min-height: 350px;
}
</style>